package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DefaultZeroValueUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.*;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.enums.BdmBalanceChangeEnum;
import com.ruoyi.system.enums.BdmMemberRuleEnum;
import com.ruoyi.system.enums.BdmUserEnum;
import com.ruoyi.system.mapper.BdmMemberRuleMapper;
import com.ruoyi.system.mapper.BdmUpdateLocationLogMapper;
import com.ruoyi.system.mapper.BdmUserMapper;
import com.ruoyi.system.service.*;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 用户会员Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-09
 */
@Service
public class BdmMemberRuleServiceImpl extends ServiceImpl<BdmMemberRuleMapper, BdmMemberRule> implements IBdmMemberRuleService {

    @Autowired
    private BdmMemberRuleMapper bdmMemberRuleMapper;

    @Autowired
    private BdmUserMapper bdmUserMapper;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private IBdmBindingChangeService bdmBindingChangeService;

    @Autowired
    private IBdmBalanceChangeService bdmBalanceChangeService;

    @Autowired
    private IBdmUserService iBdmUserService;

    @Autowired
    private BdmUpdateLocationLogMapper bdmUpdateLocationLogMapper;


    /**
     * 查询用户会员
     *
     * @param id 用户会员主键
     * @return 用户会员
     */
    @Override
    public BdmMemberRule selectBdmMemberRuleById(Long id) {
        return bdmMemberRuleMapper.selectBdmMemberRuleById(id);
    }

    /**
     * 查询用户会员列表
     *
     * @param bdmMemberRule 用户会员
     * @return 用户会员
     */
    @Override
    public List<BdmMemberRule> selectBdmMemberRuleList(BdmMemberRule bdmMemberRule) {
        return bdmMemberRuleMapper.selectBdmMemberRuleList(bdmMemberRule);
    }

    /**
     * 新增用户会员
     *
     * @param bdmMemberRule 用户会员
     * @return 结果
     */
    @Override
    public int insertBdmMemberRule(BdmMemberRule bdmMemberRule) {
        bdmMemberRule.setCreateTime(DateUtils.getNowDate());
        return bdmMemberRuleMapper.insertBdmMemberRule(bdmMemberRule);
    }

    /**
     * 修改用户会员
     *
     * @param bdmMemberRule 用户会员
     * @return 结果
     */
    @Override
    public int updateBdmMemberRule(BdmMemberRule bdmMemberRule) {
        bdmMemberRule.setUpdateTime(DateUtils.getNowDate());
        return bdmMemberRuleMapper.updateBdmMemberRule(bdmMemberRule);
    }

    /**
     * 批量删除用户会员
     *
     * @param ids 需要删除的用户会员主键
     * @return 结果
     */
    @Override
    public int deleteBdmMemberRuleByIds(Long[] ids) {
        return bdmMemberRuleMapper.deleteBdmMemberRuleByIds(ids);
    }

    /**
     * 删除用户会员信息
     *
     * @param id 用户会员主键
     * @return 结果
     */
    @Override
    public int deleteBdmMemberRuleById(Long id) {
        return bdmMemberRuleMapper.deleteBdmMemberRuleById(id);
    }

    /**
     * 统计最近五天每天的新增会员数及会员总数
     *
     * @return
     */
    @Override
    public BdmStatisticsMemberNumberVo statisticsMemberNumber() {
        Long memberCount = this.lambdaQuery().count();
        List<BdmMemberCountAndTimeVo> timeList = bdmMemberRuleMapper.statisticsMemberNumber();
        return BdmStatisticsMemberNumberVo.builder().memberNumber(memberCount).timeMemberNumber(timeList).build();
    }

    /**
     * 统计最近五天每天的会员活跃数量
     *
     * @return
     */
    @Override
    public List<Map<String, Integer>> statisticsMemberActiveNumber() {
        return bdmMemberRuleMapper.statisticsMemberActiveNumber();
    }

    /**
     * 统计会员等级分布
     *
     * @return
     */
    @Override
    public Map<String, Object> statisticsMemberLevelDistribution() {
        int userCount = bdmUserMapper.userCount();
        BdmStatisticsMemberNumberVo vo = bdmMemberRuleMapper.calculateLveleCount();
        Map<String, Object> map = new HashMap<>();
        if (vo == null) {
            map.put("oneCount", 0);
            map.put("twoCount", 0);
            map.put("threeCount", 0);
            map.put("fourCount", 0);
            map.put("fiveCount", 0);
            map.put("sixCount", 0);
            map.put("commonUserCount", userCount);
            return map;
        }
        int commonUserCount = userCount - vo.getOneCount() - vo.getTwoCount() - vo.getThreeCount() - vo.getFourCount() - vo.getFiveCount() - vo.getSixCount();
        map.put("commonUserCount", commonUserCount);
        map.put("oneCount", vo.getOneCount());
        map.put("twoCount", vo.getTwoCount());
        map.put("threeCount", vo.getThreeCount());
        map.put("fourCount", vo.getFourCount());
        map.put("fiveCount", vo.getFiveCount());
        map.put("sixCount", vo.getSixCount());
        return map;
    }

    /**
     * 查询会员列表
     *
     * @param dto
     * @return
     */
    @Override
    public List<BdmMemberRuleVo> selectPage(BdmMemberRuleDto dto) {
        return bdmMemberRuleMapper.selectPage(dto);
    }

    /**
     * 新增会员
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public boolean saveUserMember(BdmMemberSaveDto dto) {
        try {
            Long.parseLong(dto.getParentId());
        } catch (NumberFormatException e) {
            throw new RuntimeException("请输入上级推荐人id值");
        }
        if (dto.getMemberLevel() == null && dto.getMemberAgencyLevel() == null) {
            throw new RuntimeException("请输入会员等级");
        }
        String phonenumber = dto.getPhonenumber();
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(dto, sysUser);
        sysUser.setNickName(dto.getNikeName());
        sysUser.setUserName(dto.getPhonenumber());
        sysUser.setPhonenumber(dto.getPhonenumber());
        String password = "123456";
        String encryptPassword = SecurityUtils.encryptPassword(password);
        sysUser.setPassword(encryptPassword);
        sysUser.setRemark("微信用户");
        sysUser.setUserType("01");
        iSysUserService.insertUser(sysUser);

        BdmMemberRule memberRule = new BdmMemberRule();
        BeanUtils.copyProperties(dto, memberRule);
        memberRule.setSysUserid(sysUser.getUserId());
        if (dto.getMemberAgencyLevel() != null) {
            memberRule.setMemberLevel(1L);
            memberRule.setMemberName("vip");
        }
        this.insertBdmMemberRule(memberRule);

        BdmUser bdmUser = new BdmUser();
        bdmUser.setSysUserid(sysUser.getUserId());
        bdmUser.setUserPhone(phonenumber);
        if (dto.getParentId() != null) {
            bdmUser.setParentId(Long.valueOf(dto.getParentId()));
        }
        bdmUser.setCreateTime(new Date());
        bdmUserMapper.insertBdmUser(bdmUser);
        return true;
    }

    /**
     * 统计新老客户成交金额级新老客户成交数量
     *
     * @return
     */
    @Override
    public Map<String, String> statisticsUserMakeNumber() {
        return bdmUserMapper.statisticsUserMakeNumber();
    }

    /**
     * 查询会员详情
     */
    @Override
    public BdmMemberRuleGetInfoVo getInfo(Long sysUserid) {
        // 用户id   余额提现 佣金提现
        return bdmMemberRuleMapper.getInfo(sysUserid, BdmBalanceChangeEnum.BALANCE_WITHDRAW_DEPOSIT.getDescription(), BdmBalanceChangeEnum.BROKERAGE_WITHDRAW_DEPOSIT.getDescription());
    }

    /**
     * 查询推荐人
     */
    @Override
    public List<BdmReferrerVo> getReferrer(Long userId, String phonenumber) {
        if (ObjectUtils.isEmpty(userId) && StringUtils.isEmpty(phonenumber)) {
            throw new RuntimeException("查询条件必填");
        }
        return bdmMemberRuleMapper.getReferrer(userId, phonenumber);
    }


    /**
     * 修改推荐人
     */
    @Override
    @Transactional
    public int putReferrer(PutReferrerDto putReferrerDto) {
        BdmUserVo NewParent = bdmUserMapper.getBdmUserByUserId(putReferrerDto.getNewParentId());

        if (NewParent.getParentId() == putReferrerDto.getSysUserid()) {
            throw new GlobalException(NewParent.getId() + "--" + NewParent.getParentId() + "不能互为上下级");
        }

        // 新的推荐人
        BdmUser bdmUser = new BdmUser();
        bdmUser.setParentId(putReferrerDto.getNewParentId());
        bdmUser.setSysUserid(putReferrerDto.getSysUserid());
        Integer location2 = bdmUserMapper.selectUserMaxLocation(putReferrerDto.getNewParentId());
        if (location2 == null) {
            location2 = 0;
        }
        bdmUser.setLocation(location2 + 1);
        bdmUserMapper.updateBdmUserBySysUserId(bdmUser);
        // 设置默认位置
//        bdmUserMapper.setUserDefaultLocation(putReferrerDto.getSysUserid(), putReferrerDto.getParentId());
        BdmUserVo bdmUserVo4 = bdmUserMapper.selectUserByUserId(putReferrerDto.getNewParentId());
        List<BdmTeamAdminVo> helpUserId = bdmUserMapper.getHelpUserId(bdmUserVo4.getSysUserid());
        int i = 1;
        for (BdmTeamAdminVo bdmTeamAdminVo : helpUserId) {
            BdmUser bdmUser1 = new BdmUser();
            if (i > 2) {
                bdmUser1.setDistributionParentId(bdmUserVo4.getSysUserid());
            } else {
                Long parentId = bdmUserVo4.getParentId();
                if (parentId != null) {
                    bdmUser1.setDistributionParentId(parentId);
                }
            }
            if (bdmUser1.getDistributionParentId() != null) {
                bdmUserMapper.updateBdmUserBySysUserId(bdmUser1);
            }
            bdmUser1.setLocation(i++);
            bdmUser1.setSysUserid(bdmTeamAdminVo.getUserId());
            bdmUserMapper.updateBdmUserBySysUserId(bdmUser1);
        }

        // 原推荐人下级位置变更
        // 上级
        BdmUserVo bdmUserVo3 = bdmUserMapper.selectUserByUserId(putReferrerDto.getParentId());
        // 上级的下级位置列表
        List<BdmTeamAdminVo> helpUserId1 = bdmUserMapper.getHelpUserId(putReferrerDto.getParentId());
        int i1 = 1;
        for (BdmTeamAdminVo bdmTeamAdminVo : helpUserId1) {
            BdmUser bdmUser1 = new BdmUser();
            if (i1 > 2) {
                bdmUser1.setDistributionParentId(bdmUserVo3.getSysUserid());
            } else {
                Long parentId = bdmUserVo3.getParentId();
                if (parentId != null) {
                    bdmUser1.setDistributionParentId(parentId);
                }
            }
            if (bdmUser1.getDistributionParentId() != null) {
                bdmUserMapper.updateBdmUserBySysUserId(bdmUser1);
            }
            bdmUser1.setLocation(i1++);
            bdmUser1.setSysUserid(bdmTeamAdminVo.getUserId());
            bdmUserMapper.updateBdmUserBySysUserId(bdmUser1);
        }

        Date nowDate = DateUtils.getNowDate();
        Long userId = SecurityUtils.getUserId();
        //插入推荐人变动表
        BdmBindingChange bdmBindingChange = new BdmBindingChange();
        bdmBindingChange.setUserId(putReferrerDto.getSysUserid());
        bdmBindingChange.setBeforeChangeId(putReferrerDto.getParentId());
        bdmBindingChange.setBeforeChangeName(putReferrerDto.getParentName());
        bdmBindingChange.setAfterChangeId(putReferrerDto.getNewParentId());
        bdmBindingChange.setAfterChangeName(putReferrerDto.getNewParentName());
        bdmBindingChange.setChangeTime(nowDate);
        bdmBindingChange.setCreateBy(userId.toString());
        bdmBindingChange.setCreateTime(nowDate);
        bdmBindingChange.setUpdateBy(userId.toString());
        bdmBindingChange.setUpdateTime(nowDate);
        bdmBindingChangeService.save(bdmBindingChange);
        //检测是否有闭环
        iBdmUserService.checkUpUser(new HashMap<String, String>(), putReferrerDto.getSysUserid());
        i1 = 1;
        i = 1;
        return 1;
    }

    /**
     * 修改余额
     */
    @Override
    @Transactional
    public int modifyBalance(ModifyBalanceDto modifyBalanceDto) {
        LambdaQueryWrapper<BdmUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(BdmUser::getSysUserid, modifyBalanceDto.getUserId());
        BdmUser bdmUser = bdmUserMapper.selectOne(lqw);
        if (ObjectUtils.isEmpty(bdmUser)) {
            throw new RuntimeException("用户不存在");
        }
        int i = bdmUserMapper.modifyBalance(modifyBalanceDto);
        if (i == 0) {
            throw new RuntimeException("余额不足");
        }
        //记录余额积分变动表
        BdmBalanceChange bdmBalanceChange = BdmBalanceChange.getBdmBalanceChange(modifyBalanceDto.getUserId(),
                "",
                String.valueOf(Math.abs(Double.parseDouble(modifyBalanceDto.getBalance().toString()))),
                bdmUser.getRemainingSum().toString(),
                bdmUser.getRemainingSum().add(modifyBalanceDto.getBalance()).toString(),
                Long.parseLong(BdmBalanceChangeEnum.BALANCE.getType()),
                modifyBalanceDto.getBalance().compareTo(new BigDecimal("0")) >= 0 ? Long.parseLong(BdmBalanceChangeEnum.ADD.getType()) : Long.parseLong(BdmBalanceChangeEnum.SUBTRACT.getType()),
                modifyBalanceDto.getBalance().compareTo(new BigDecimal("0")) >= 0 ? BdmBalanceChangeEnum.SYSTEM_ADDITION.getDescription() : BdmBalanceChangeEnum.SYSTEMATIC_DEDUCTION.getDescription()
        );


        boolean save = bdmBalanceChangeService.save(bdmBalanceChange);
        if (!save) {
            throw new RuntimeException("记录失败");
        }
        return i;
    }

    /**
     * 修改积分
     */
    @Override
    @Transactional
    public int modifyIntegral(ModifyIntegralDto modifyIntegralDto) {
        LambdaQueryWrapper<BdmUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(BdmUser::getSysUserid, modifyIntegralDto.getUserId());
        BdmUser bdmUser = bdmUserMapper.selectOne(lqw);
        if (ObjectUtils.isEmpty(bdmUser)) {
            throw new RuntimeException("用户不存在");
        }

        int i = bdmUserMapper.modifyIntegral(modifyIntegralDto);
        if (i == 0) {
            throw new RuntimeException("积分不足");
        }
        //记录余额积分变动表
        BdmBalanceChange bdmBalanceChange = BdmBalanceChange.getBdmBalanceChange(modifyIntegralDto.getUserId(),
                "",
                String.valueOf(Math.abs(Double.parseDouble(modifyIntegralDto.getIntegral().toString()))),
                bdmUser.getCreditScore(),
                String.valueOf(Long.parseLong(DefaultZeroValueUtil.getValue(bdmUser.getCreditScore())) + modifyIntegralDto.getIntegral()),
                Long.parseLong(BdmBalanceChangeEnum.INTEGRAL.getType()),
                modifyIntegralDto.getIntegral() >= 0 ? Long.parseLong(BdmBalanceChangeEnum.ADD.getType()) : Long.parseLong(BdmBalanceChangeEnum.SUBTRACT.getType()),
                modifyIntegralDto.getIntegral() >= 0 ? BdmBalanceChangeEnum.SYSTEM_ADDITION.getDescription() : BdmBalanceChangeEnum.SYSTEMATIC_DEDUCTION.getDescription()
        );
        boolean save = bdmBalanceChangeService.save(bdmBalanceChange);
        if (!save) {
            throw new RuntimeException("记录失败");
        }
        return i;
    }

    /**
     * 重置支付密码
     */
    @Override
    public int putPaymentCode(Long userId) {
        return baseMapper.putPaymentCode(userId, SecurityUtils.encryptPassword(BdmUserEnum.DEFAULT_PAYMENT_PASSWORD.getType()));
    }

    @Override
    public int changeMembershipLevel(BdmChangeMembershipLevelDto bdmChangeMembershipLevelDto) {
        BdmMemberRuleEnum[] values = BdmMemberRuleEnum.values();
        String levelName = "";
        for (BdmMemberRuleEnum value : values) {
            if (value.getLevel().equals(bdmChangeMembershipLevelDto.getLevel())) {
                levelName = value.getDescription();
            }
        }
        if (bdmChangeMembershipLevelDto.getLevel().equals(0L)) {
            return bdmMemberRuleMapper.delete(new LambdaQueryWrapper<BdmMemberRule>().eq(BdmMemberRule::getSysUserid, bdmChangeMembershipLevelDto.getUserId()));
        }
        BdmMemberRule memberRule = lambdaQuery().eq(BdmMemberRule::getSysUserid, bdmChangeMembershipLevelDto.getUserId()).one();
        if (memberRule == null) {
            memberRule = new BdmMemberRule();
            if (bdmChangeMembershipLevelDto.getLevel() > 2) {
                BdmMemberRule bdmMemberRule = bdmMemberRuleMapper.selectOne(Wrappers.<BdmMemberRule>lambdaQuery().eq(BdmMemberRule::getSysUserid, bdmChangeMembershipLevelDto.getUserId()));
                if (bdmMemberRule == null) {
                    memberRule.setMemberLevel(1L);
                    memberRule.setMemberName("vip");
                }
                if (bdmMemberRule != null && bdmMemberRule.getMemberLevel() != null) {
                    memberRule.setMemberLevel(1L);
                    memberRule.setMemberName("vip");
                }
                memberRule.setMemberAgencyLevelName(levelName);
                memberRule.setMemberAgencyLevel(bdmChangeMembershipLevelDto.getLevel());
            } else {
                memberRule.setMemberName(levelName);
                memberRule.setMemberLevel(bdmChangeMembershipLevelDto.getLevel());
            }
            memberRule.setSysUserid(bdmChangeMembershipLevelDto.getUserId());
            memberRule.setState(1L);
            memberRule.setCreateTime(new Date());
            return bdmMemberRuleMapper.insertBdmMemberRule(memberRule);
        }
        return baseMapper.changeMembershipLevel(bdmChangeMembershipLevelDto.getUserId(), bdmChangeMembershipLevelDto.getLevel(), levelName);
    }

    /**
     * 团队管理列表
     *
     * @param dto
     * @return
     */
    @Override
    public List<BdmTeamAdminVo> getTeamAdminList(BdmMemberRuleDto dto) {
        List<BdmTeamAdminVo> list = baseMapper.getTeamAdminList(dto);
        for (BdmTeamAdminVo item : list) {
            List<Long> vipUserIdList = bdmUserMapper.getSubordinateVip(item.getUserId());
            // 找出下级购买商品id(推荐关系)
            BigDecimal zero = BigDecimal.ZERO;
            for (Long userId : vipUserIdList) {
                BdmUserVo bdmUserVo = bdmUserMapper.getBdmUserByUserId(userId);
                if (bdmUserVo != null) {
                    List<Long> lowerUserIds = bdmUserMapper.getLocationLowerUserId(bdmUserVo.getSysUserid());
                    if (bdmUserVo.getLocation().equals(1)) {
                        if (CollectionUtils.isNotEmpty(lowerUserIds)) {
                            BigDecimal number = bdmUserMapper.getUserMoney(lowerUserIds);
                            zero = zero.add(number);
                            item.setOnePerformance(number);
                        }
                    }
                    if (bdmUserVo.getLocation().equals(2)) {
                        if (CollectionUtils.isNotEmpty(lowerUserIds)) {
                            BigDecimal number = bdmUserMapper.getUserMoney(lowerUserIds);
                            zero = zero.add(number);
                            item.setTwoPerformance(number);
                        }
                    }
                }
            }
            item.setPerformance(zero);
            item.setTeamAdminVos(bdmUserMapper.getHelpUserId(item.getUserId()));
        }
        return list;
    }

    /**
     * 团队管理用户换位编辑
     *
     * @param dtos
     * @return
     */
    @Override
    @Transactional
    public boolean teamUserExchange(List<BdmMemberRuleDto> dtos) {
        BdmUserVo bdmUserVo = bdmUserMapper.selectUserByUserId(dtos.get(0).getUserId());
        Long parentId = bdmUserVo.getParentId();
        BdmUserVo bdmUserVo1 = bdmUserMapper.selectUserByUserId(parentId);
        for (BdmMemberRuleDto dto : dtos) {
            BdmUser bdmUser = new BdmUser();
            bdmUser.setSysUserid(dto.getUserId());
            String location = dto.getLocation();
            Integer location1 = Integer.parseInt(location);
            if (location1 > 2) {
                bdmUser.setDistributionParentId(bdmUserVo1.getSysUserid());
            } else {
                Long parentId1 = bdmUserVo1.getParentId();
                if (parentId1 != null) {
                    bdmUser.setDistributionParentId(parentId1);
                }

            }
            if (bdmUser.getDistributionParentId() != null) {
                bdmUserMapper.updateBdmUserBySysUserId(bdmUser);
            }
            BdmUpdateLocationLog bdmUpdateLocationLog = new BdmUpdateLocationLog();
            bdmUpdateLocationLog.setParentId(parentId);
            BdmUserVo bdmUserVo2 = bdmUserMapper.selectUserByUserId(dto.getUserId());
            bdmUpdateLocationLog.setUserId(bdmUserVo2.getSysUserid());
            Integer location2 = bdmUserVo2.getLocation();
            if (location2 != null) {
                bdmUpdateLocationLog.setBeforeLocation(Long.valueOf(location2));
            }
            bdmUpdateLocationLog.setAfterLocation(Long.valueOf(location1));
            bdmUpdateLocationLog.setCreateTime(new Date());
            bdmUpdateLocationLog.setCreateBy(SecurityUtils.getUsername());
            if (!Objects.equals(bdmUserVo2.getLocation(), location1)) {
                bdmUpdateLocationLogMapper.insertBdmUpdateLocationLog(bdmUpdateLocationLog);
            }
        }
        bdmUserMapper.teamUserExchange(dtos);
        return true;
    }

    /**
     * 会员列表 选择推荐人
     *
     * @param dto
     * @return
     */
    @Override
    public List<BdmMemberRuleVo> selectPageList(BdmMemberRuleDto dto) {
        return baseMapper.selectPageList(dto);
    }


    /**
     * 后台排序专用
     */
    @Override
    public void sort() {
        for (BdmMemberRule bdmMemberRule : bdmMemberRuleMapper.selectBdmMemberRuleList(new BdmMemberRule())) {
            Long sysUserid = bdmMemberRule.getSysUserid();
            BdmUserVo bdmUserVo = bdmUserMapper.selectUserByUserId(sysUserid);
            List<BdmTeamAdminVo> helpUserId = bdmUserMapper.getHelpUserId(sysUserid);
            if (helpUserId != null) {
                int i = 1;
                for (BdmTeamAdminVo bdmTeamAdminVo : helpUserId) {
                    BdmUser bdmUser1 = new BdmUser();
                    if (i > 2) {
                        bdmUser1.setDistributionParentId(bdmUserVo.getSysUserid());
                    } else {
                        Long parentId = bdmUserVo.getParentId();
                        if (parentId != null) {
                            bdmUser1.setDistributionParentId(parentId);
                        }
                    }
                    if (bdmUser1.getDistributionParentId() != null) {
                        bdmUserMapper.updateBdmUserBySysUserId(bdmUser1);
                    }
                    bdmUser1.setLocation(i++);
                    bdmUser1.setSysUserid(bdmTeamAdminVo.getUserId());
                    bdmUserMapper.updateBdmUserBySysUserId(bdmUser1);
                }
                i = 1;
            }
        }
    }
}
